//
//  MoyaCacheDateList.swift
//  Common
//
//  Created by 我骑着蜗牛走天下 on 2025/11/14.
//

import UIKit

class MoyaCacheDateList: ViewController<MoyaCacheDateListView> {
    
    var dateList: [(title: String,url: URL)?] = []{
        didSet{
            contatiner.tableView.reloadData()
        }
    }
    
    var didSelectBlock: (_ tupple: (title: String,url: URL)?) -> Void = {_ in}
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "历史启动时间列表"
        
        contatiner.tableView.delegate = self
        contatiner.tableView.dataSource = self
        
        dateList = [nil] + NetworkCacheManager.shared.listAllFilesInDocuments()
        
    }
    
}

extension MoyaCacheDateList: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        dateList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.description(), for: indexPath)
        cell.selectionStyle = .none
        
        cell.textLabel?.text = dateList[indexPath.row]?.title ?? "当前"
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        didSelectBlock( dateList[indexPath.row] )
        navigationController?.popViewController(animated: true)
    }
    
}


class MoyaCacheDateListView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .white
        
        tableView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(tableView)
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: self.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            tableView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: self.trailingAnchor)
        ])
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var tableView: UITableView = {
        let table = UITableView()
        table.rowHeight = 60
        table.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.description())
        return table
    }()
    
}
